package com.file.upload.fileupload;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
public class UploadFile {

    @Value("${fileUploadPath}")
    private String uploadPath;

    /**
     * 单文件上传
     *
     * @param file
     * @param request
     * @return
     */
    @PostMapping("/upFile")
    @ResponseBody
    @CrossOrigin
    public Map<String,String> upload(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response ) {

//        response.setHeader("Access-Control-Allow-Origin", "*");
//        response.setHeader("Access-Control-Allow-Methods", "*");
//        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");
//        response.setContentType("application/json");
//        response.setCharacterEncoding("utf-8");
       
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String datePath = dateFormat.format(new Date());
        String fileName = UUID.randomUUID().toString().replace("-","");
        Map<String,String> map = new HashMap<>();

        if (!file.isEmpty()) {
            StringBuffer filePath = new StringBuffer(uploadPath).append("/").append(datePath).append("/").append(fileName).append(".jpg");
            File saveFile = new File(filePath.toString());
            if (!saveFile.getParentFile().exists()) {
                saveFile.getParentFile().mkdirs();
            }
            try {
                BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(saveFile));
                out.write(file.getBytes());
                out.flush();
                out.close();
                map.put("info","上传成功");
                map.put("status","1");
                String[] split = saveFile.getPath().split("photos");
                map.put("path",split[1]);
                return map;
            } catch (Exception e) {
                e.printStackTrace();
                map.put("info","上传失败，请联系管理员处理");
                map.put("status","0");
                return map;
            }
        } else {
            map.put("info","文件不能为空");
            map.put("status","0");
            return map;
        }
    }

}
